6. Sparse Columns
The sparse column feature is new in SQL Server 2008. You can declare a column using the sparse keyword, and anytime a NULL value is entered in the column, that NULL value will not use any disk space. Sounds good, right? But there is a catch.
Sparse columns require an extra 4 bytes of storage for each non-NULL, fixed-length value in the table. So while they require zero bytes to store a NULL value, they require extra space to store non-NULL values. Therefore, it is very important to have a reasonable ratio of NULL to non-NULL values. Otherwise, use of the sparse columns feature will end up costing you disk space rather than saving it.
The fewer bytes a data type requires, the higher the percentage of NULL
values you will need in the column in order to save space via the
sparse columns feature. There is a table in SQL Server Books Online you
can use to determine the estimated space savings per data type (see
"Using Sparse Columns" at http://msdn.microsoft.com/en-us/library/cc280604.aspx).
Sparse columns must allow NULL values and cannot include the following data types:
Geography
Geometry
Image
ntext
Text
Timestamp
User-defined data types
Let's look at the sample code in Listing 17.
Address Lines 1 and 2 are required, so you cannot define them as sparse
columns. Address Lines 3 and 4 are not required, but they are often
used and would not be good candidates for sparse columns. However,
Address Lines 5 and 6 are rarely populated, so you can define them as
sparse and benefit from the disk savings.
Example 17. Syntax for Creating a Table Using Sparse Columns
USE AdventureWorks2008 GO
--Drop the table if it currently exists IF OBJECT_ID('dbo.CustInfo', 'U') IS NOT NULL DROP TABLE dbo.CustInfo;
--Create the table CREATE TABLE CustInfo (CustID INT PRIMARY KEY, Addr_Line1 VARCHAR(100) NOT NULL, Addr_Line2 VARCHAR(100) NOT NULL, Addr_Line3 VARCHAR(100) NULL, Addr_Line4 VARCHAR(100) NULL, Addr_Line5 VARCHAR(100) SPARSE NULL, Addr_Line6 VARCHAR(100) SPARSE NULL)
|
If you want to add the SPARSE option to a column in a table that already exists, you can use the ALTER TABLE statement. Listing 18 shows how to use the ALTER TABLE statement to change the Addr_Line4 column in the CustInfo table to a sparse column. If you want to drop the SPARSE option from a column, all you need to do is change the ADD keyword to DROP, as shown in Listing 19.
Example 18. Syntax for Adding the SPARSE Option to a Column Using the ALTER TABLE Statement
ALTER TABLE CustInfo ALTER COLUMN Addr_Line4 ADD SPARSE
|
Example 19. Syntax for Dropping the SPARSE Option from a Column Using the ALTER TABLE Statement
ALTER TABLE CustInfo ALTER COLUMN Addr_Line4 DROP SPARSE